package com.jing.serial.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

@Configuration
@EnableScheduling
public class TaskConfig {

    // 保存所有的WebSocket会话
    private final Set<WebSocketSession> sessions = new HashSet<>();

    // 在WebSocket连接建立时，添加会话到集合
    public void addSession(WebSocketSession session) {
        sessions.add(session);
    }

    // 在WebSocket连接关闭时，从集合中移除会话
    public void removeSession(WebSocketSession session) {
        sessions.remove(session);
    }

    // 定时任务，每5秒发送一次消息
    @Scheduled(cron = "0/5 * * * * ? ")
    public void sendPeriodicMessages() {
        for (WebSocketSession session : sessions) {
            if (session.isOpen()) {
                try {
                    // 获取当前时间
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                    String currentTime = dateFormat.format(new Date());

                    session.sendMessage(new TextMessage("hello, from service "+currentTime));
                    System.out.println("\"hello, from service\" " + currentTime);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else {
                System.out.println("websocket is no connected!");
            }
        }
    }
}